package com.example.tms.tools;

import com.example.tms.bean.PermsView;
import com.example.tms.bean.RoleView;
import com.example.tms.bean.UserView;
import com.example.tms.mapper.PermsVMapper;
import com.example.tms.mapper.RoleVMapper;
import com.example.tms.mapper.UserVMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证授权
 */
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserVMapper userVMapper;

    @Autowired
    private RoleVMapper roleVMapper;

    @Autowired
    private PermsVMapper permsVMapper;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        logger.info("用户名"+username);
        UserView user = userVMapper.findByYhm(username);
        List<String> permsList = new ArrayList<>();
        List<RoleView> roleViews = roleVMapper.findByYhid(user.getYhid());
        for(RoleView roleView : roleViews){
            List<PermsView> permsViews = permsVMapper.findByJsid(roleView.getJsid());
            for(PermsView permsView : permsViews){
                permsList.add(permsView.getQxid());
            }
        }
        user.setPermsList(permsList);
        return new SimpleAuthenticationInfo(user, user.getMima(),this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal){
        UserView user=(UserView) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(user.getPermsList());//将权限放入shiro中.
        return info;
    }

}
